/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.client.ex;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by Peter on 2016/9/5.
 */
public class CheckBoxHeadRenderer implements TableCellRenderer {

    private CheckBoxHeadModal tableModel;
    private JTableHeader tableHeader;
    private JCheckBox selectBox;

    public CheckBoxHeadRenderer(JTable table) {
        setting(table, true);
    }

    public CheckBoxHeadRenderer(JTable table, boolean isSelected) {
        setting(table, isSelected);
    }

    private void setting(JTable table, boolean isSelected) {
        this.tableModel = (CheckBoxHeadModal) table.getModel();
        this.tableHeader = table.getTableHeader();
        selectBox = new JCheckBox();
        selectBox.setSelected(isSelected);
        tableHeader.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    int selectColumn = tableHeader.columnAtPoint(e.getPoint());
                    if (selectColumn == 0) {
                        boolean value = !selectBox.isSelected();
                        selectBox.setSelected(value);
                        tableModel.selectAll(value);
                        tableHeader.repaint();
                    }
                }
            }
        });
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        String valueStr = (String) value;
        JLabel label = new JLabel(valueStr);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        selectBox.setHorizontalAlignment(SwingConstants.CENTER);
        selectBox.setBorderPainted(true);
        JComponent component = (column == 0) ? selectBox : label;

        component.setForeground(tableHeader.getForeground());
        component.setBackground(tableHeader.getBackground());
        component.setFont(tableHeader.getFont());
        component.setBorder(UIManager.getBorder("TableHeader.cellBorder"));

        return component;
    }

    public void setCheckboxSelect(boolean isChecked) {
        selectBox.setSelected(isChecked);
        tableModel.selectAll(isChecked);
        tableHeader.repaint();
    }

    public void setCheckAll(boolean flag) {
        selectBox.setSelected(flag);
        tableHeader.repaint();
    }

    public boolean isSelected() {
        return selectBox.isSelected();
    }
}
